interface DataListCellType {
  text: string;
  active: boolean;
}
const TAB_TAP_EVENT = "tabtap";
Component({
  options: {
    virtualHost: true,
    pureDataPattern: /^_/,
  },
  behaviors: [require("@/behaviors/com-base-behavior")],
  properties: {
    frame: {
      type: Array,
      value: [],
    },
    active: {
      type: Number,
      value: 0,
    },
  },
  data: {
    list: [] as DataListCellType[],
    _curIndex: 0,
    scrollLeft: 0,
    _maxScrollWidth: 0,
    _stepScale: 0.3,
    _stepWidth: 0,
    _containerWidth: 0,
  },
  methods: {
    celltap(e: WechatMiniprogram.TouchEvent) {
      let index: number = e.currentTarget.dataset.index;
      if (index == this.data._curIndex) {
        return;
      }
      this.data.list[index].active = true;
      this.setData({
        ["list[" + index + "].active"]: true,
        ["list[" + this.data._curIndex + "].active"]: false,
      });
      this.data._curIndex = index;
      this._autoScroll(e, index);
      this.triggerEvent(TAB_TAP_EVENT, {
        index,
        data: this.properties.frame[index],
      });
    },
    scrollEnd(e: WechatMiniprogram.ScrollViewDragEnd) {
      console.log("scrollEnd", e.detail.scrollLeft);
      this.data.scrollLeft = e.detail.scrollLeft;
    },
    _autoScroll(e: WechatMiniprogram.TouchEvent, itemIndex: number) {
      this.createSelectorQuery()
        .select(`.cell-${itemIndex}`)
        .boundingClientRect((itemRect) => {
          const itemLeft = itemRect.left; // 点击元素左边界距离屏幕左侧的距离
          const itemRight = itemRect.right; // 点击元素右边界距离屏幕左侧的距离
          let scrollLeft = this.data.scrollLeft;
          let edgeThreshold = this.data._stepWidth;
          let containerWidth = this.data._containerWidth;
          // 判断是否靠近边缘（示例：20%区域）
          const isNearLeftEdge = itemLeft < edgeThreshold;
          const isNearRightEdge = containerWidth - itemRight < edgeThreshold;
          console.log(itemRect, edgeThreshold, isNearRightEdge);

          // 自动滚动逻辑
          if (isNearLeftEdge) {
            const srollWith = scrollLeft - this.data._stepWidth;
            console.log("left", srollWith);
            if (scrollLeft <= 0) {
              return;
            }
            this.setData({
              scrollLeft: Math.max(0, srollWith), // 向左滚动一屏
            });
          } else if (isNearRightEdge) {
            const maxStep = this.data._maxScrollWidth;
            const srollWith = scrollLeft + this.data._stepWidth;
            let desWith = Math.min(srollWith, maxStep);
            console.log("right", desWith);
            if (scrollLeft >= maxStep) {
              return;
            }
            this.setData({
              scrollLeft: desWith,
            });
          }
        })
        .exec();
    },
  },
  lifetimes: {
    attached() {
      let temp = this.properties.frame.map((v) => {
        let res = {
          text: v.text,
          active: v.active ?? false,
        };
        return res;
      });
      let activeIndex =
        this.properties.active > temp.length - 1 || this.properties.active < 0
          ? 0
          : this.properties.active;
      temp[activeIndex].active = true;
      this.data._curIndex = activeIndex;
      this.setData({ list: temp });
    },
    ready() {
      // 获取滚动区域总宽度（所有子元素宽度之和）
      const query = this.createSelectorQuery();
      query
        .select(".m-tab-bar")
        .boundingClientRect()
        .selectAll(".m-tab-bar-cell")
        .boundingClientRect()
        .exec((des) => {
          let rect: WechatMiniprogram.BoundingClientRectCallbackResult = des[0];
          this.data._stepWidth = rect.width * this.data._stepScale;
          const rects: WechatMiniprogram.BoundingClientRectCallbackResult[] =
            des[1];
          const totalWidth = rects.reduce((sum, rect, index) => {
            console.log(index, rect.width);
            return sum + rect.width;
          }, 0);
          this.data._maxScrollWidth = totalWidth - rect.width;
          this.data._containerWidth = rect.width;
          console.log("tab-bar,ready", {
            containerWidth: rect.width,
            maxScrollWidth: this.data._maxScrollWidth,
            totalWidth,
          });
        });
    },
  },
});
